<!--
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2019-07-04 01:36:52
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-07 05:33:18
 -->
<template>
  <div>
    <div class="margin-w-auto">
      <el-form
        ref="registerForm"
        size="medium"
        :model="registerForm"
        :rules="loginRules"
        label-position="left"
      >
        <el-form-item prop="username">
          <el-input
            v-model.number="registerForm.username"
            placeholder="用户名"
          >
            <template slot="prepend">
              <svg-icon icon-class="user" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="card">
          <el-input
            v-model.trim="registerForm.card"
            placeholder="注册码"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            :key="passwordType"
            v-model.trim="registerForm.password"
            placeholder="密码(6-14位非空字符)"
            :type="passwordType"
            @keyup.enter.native="handleRegister"
          >
            <template slot="prepend">
              <svg-icon icon-class="password" />
            </template>
            <template slot="append">
              <svg-icon
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                @click="showPwd"
              />
            </template>
          </el-input>
        </el-form-item>
        <div id="r" />
        <el-button
          class="wfull"
          size="medium"
          :loading="loading.submit"
          type="primary"
          @click.native.prevent="handleRegister"
        >立即进入</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import { validateRegisterName, validatePassword } from '@/utils/validate.js'
import logoUrl from '@/assets/images/logo-big.png'
import { getVerifyCode } from '@/api/sys/tenant.js'
import { getValidator } from '@/utils/validate.js'
import config from '@/config/index.js'

const defaultSendCodeText = '获取验证码'

export default {
  name: 'Register',
  mixins: [],
  data() {
    return {
      valicode: null,
      logoUrl: logoUrl,
      loading: {},
      disabled: { submit: true, code: false },
      sendCodeText: defaultSendCodeText,
      registerForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateRegisterName }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        card: [{ required: true, trigger: 'blur', message: '请输入注册码' }]
      },
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    },
    'registerForm.token': {
      handler(val) {
        if (val && val !== '') {
          this.$set(this.disabled, 'submit', false)
        } else {
          this.$set(this.disabled, 'submit', true)
        }
      }
    }
  },
  mounted() {
  },
  methods: {
    btnSendVerifyCode() {
      const { username } = this.registerForm
      const v = getValidator()
      if (username === '' || username === null || username === undefined) {
        return this.$message.error('手机号不能为空！')
      }
      if (!v.isPhone(String(username))) {
        return this.$message.error('手机号格式不正确！')
      }
      this.valicode.show()
      this.valicode.reload()
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    initData() {
      const appId = config.appId
      const _this = this
      // eslint-disable-next-line no-undef
      const valicode = _dx.Captcha(document.getElementById('r'), {
        appId, // appId，在控制台中“应用管理”或“应用配置”模块获取
        style: 'popup',
        inlineFloatPosition: 'up'
      })
      valicode.on('verifySuccess', function(token) {
        _this.$set(_this.registerForm, 'token', token)
        _this.valicode.hide()
        _this.sendCode()
      })
      valicode.on('passByServer', function(security_code) {
        // 说明：security_code = token + ':' + constID
        console.log('passByServer is: ' + security_code)
      })
      this.valicode = valicode
    },
    setSendBtnGay() {
      let i = 60
      const _this = this
      _this.$set(_this.disabled, 'code', true)
      const inter = setInterval(() => {
        const text = `重发(${i}秒)`
        _this.sendCodeText = text
        i--
        if (i === 0) {
          clearInterval(inter)
          _this.$set(_this.disabled, 'code', false)
          _this.sendCodeText = defaultSendCodeText
        }
      }, 1000)
    },
    sendCode() {
      const { username, token } = this.registerForm
      const params = { phoneNo: String(username), token }
      getVerifyCode(params).then(res => {
        if (res.data.flag) {
          this.setSendBtnGay()
        } else {
          this.$message.error(res.data.message || '发送失败！')
        }
      })
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.$set(this.loading, 'submit', true)
          this.$store.dispatch('user/register', this.registerForm).then((res) => {
            this.$router.push({ path: this.redirect || '/' })
            this.$set(this.loading, 'submit', false)
          }).catch(() => {
            this.$set(this.loading, 'submit', false)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">

</style>
